import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import { getToken } from '@/utils/storage'
import Home from '@/views/Layout/Home'
import Articles from '@/views/Layout/Articles'
import Pictures from '@/views/Layout/Pictures'
import AddArticle from '@/views/Layout/Articles/add'
import Comments from '@/views/Layout/Comments/Comments.vue'
import Fans from '@/views/Layout/Fans/index.vue'
import Settings from '@/views/Layout/Settings'
// import EditArticle from '@/views/Layout/Articles/edit'
import NotFound from '@/views/NotFound'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '/',
          component: Home
        },
        {
          path: '/articles',
          component: Articles
        },
        {
          path: '/pictures',
          component: Pictures
        },
        {
          path: '/addArticle',
          component: AddArticle
        },
        {
          path: '/edit-article/:id',
          component: AddArticle
        },
        {
          path: '/comments',
          component: Comments
        },
        {
          path: '/fans',
          component: Fans
        },
        {
          path: '/settings',
          component: Settings
        }
      ]
    },
    {
      // 匹配所有的路由规则
      path: '*',
      component: NotFound
    }
  ]
})

// 配置路由的导航守卫
// beforeEach提供的函数会在所有的路由发生跳转之前。
// next()   如果直接调用next()代表放行   next('/login') 代表跳转到login
// 1. 如果有token, 或者去登录 就直接放行
// 2. 否则就拦截到登录去
router.beforeEach((to, from, next) => {
  // console.log('我是导航守卫')
  // console.log('to', to)
  // console.log('from', from)
  const token = getToken()
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
